import React, { PureComponent } from 'react';
import { Card, message, Modal, Select as AntdSelect, Button } from 'antd'
import { PageContainer } from '@ant-design/pro-layout';
import { getHandle } from '@/services/baseurl'
import { simulationPoints } from '@/services/setting'
import { dev, checkHost, hasProgressFunc, stopExamIfTimeNotEnough, learnTime } from '@/utils/utils'
import { submitExam, topicQuestionBank, clearWrong,getExamList } from '@/services/studentExam'
import { history } from 'umi'
import { getStudentSubject } from '@/services/studentPractice'
import styles from './index.less'
import { isHangda } from '../../../utils/utils';
class Select extends PureComponent<any, any> {
    constructor(props: any) {
        super(props)
        const userinfo = JSON.parse(localStorage.getItem('userinfo') || '{}');
        const hasTwo: any = localStorage.getItem('hasTwo') || 2;
        const openid = userinfo.openid;
        if (checkHost()) {
            if (!openid && hasTwo != 1) {
                Modal.confirm({
                    title: <p style={{ fontSize: 20, marginTop: -3 }}>操作提醒</p>,
                    content: <p style={{ fontSize: 18 }}>新用户请绑定您的微信账号解锁培训练习权限，绑定成功后每次登录平台请使用微信进行扫码登录即可。</p>,
                    okText: '去绑定',
                    style: { fontSize: 30, color: "#f60" },
                    onOk: () => {
                        location.href = `https://${window.location.host}/index/index/login_weixin`;
                    },
                });
                history.goBack();
            }
        }


        this.state = {
            data: [],
            cascaderData: [],
            subject: "",
            subjects: '',
            showManual:false
        };
    }
    checkPaperList = (subject:any)=>{
        const uid = localStorage.getItem("id") || "";
        getExamList({uid,subject,type:'3'}).then(res=>{
            if(res&&res[0]){
                this.setState({
                    showManual:true
                })
            }else{
                this.setState({
                    showManual:false
                })
            }
        })
    }
    componentDidMount() {
        const uid = localStorage.getItem("id") || "";
        const percent = localStorage.getItem("percent") || "";
        getStudentSubject({ uid }).then((res) => {
            if (!res.subjects) return;
            this.setState({
                cascaderData: res.subjects,
                subject: [res.subjects[0].id],
                subjects: [res.subjects[0].title],
            });
            this.checkPaperList(res.subjects[0].id)
            if (hasProgressFunc() && Number(percent) < learnTime() && stopExamIfTimeNotEnough()) {
                return Modal.info({
                    title: <p style={{ fontSize: 20, marginTop: -3 }}>操作提醒</p>,
                    content: <p style={{ fontSize: 18 }}>您的学习时长未达标，请到学时达标后再进行模拟考试</p>,
                    okText: '确定',
                    style: { fontSize: 30, color: "#f60" },
                    onOk: () => {
                        history.goBack();
                    },
                });
            }
        });
    }
    changeSubject = (e: any, d: any) => {
        this.setState({
            subject: e,
            subjects: d.children
        })
        this.checkPaperList(e)
    }
    clearWrong = (type: string) => () => {
        Modal.confirm({
            title: `确定要清除${type === '1' ? '错题' : '标记题'}？`,
            onOk: () => {
                clearWrong({ type }).then(res => {
                    if (res.static === 1) {
                        message.success('已清除')
                    }
                })
            }
        })
    }
    jumpExam = (type: number) => () => {
        const { subject, subjects } = this.state;
        const uid = localStorage.getItem("id") || '';
        const operation = `进入了模拟考试（${type === 2 ? '我的错题' : '标记试题'}）`;
        topicQuestionBank({ id: uid, type, subject }).then(res => {
            if (res[0][0] || res[1][0] || res[2][0]) {
                simulationPoints(uid).then((res) => {
                    if (res.status === 1) {
                        getHandle({ operation });
                        submitExam({
                            duration: "",
                            pid: '',
                            uid,
                            grade: "0",
                            total: "0",
                            correct_total: "0",
                            did_total: "0",
                            topic: [[], [], []],
                            answer: [[], [], []],
                            label: '',
                            wrong: '',
                            id: "",
                        }).then((res) => {
                            this.props.history.push(`/examPage2/${res.id}/${type}/${subject}/${subjects}/2`)
                            // window.open(dev + `#/examPage2/${res.id}/${type}/${subject}/${subjects}/2`, '考试中心', 'width=' + (window.screen.availWidth - 10) + ',height=' + (window.screen.availHeight - 20) + ',top=0,left=0,resizable=no,status=yes,menubar=no,scrollbars=yes');
                        });
                    } else {
                        message.error("积分不足");
                    }
                });
            } else {
                message.error('题库中没有题')
            }

        })


    }
    render() {
        const { subject, subjects, cascaderData ,showManual} = this.state;
        return (
            <PageContainer>
                <Card>
                    <AntdSelect style={{ width: '50%', margin: 'auto', display: 'block' }} size="large" onChange={this.changeSubject} value={subject}>
                        {
                            cascaderData.map((item: any) => {
                                return <AntdSelect.Option key={item.id} value={item.id}>{item.title}</AntdSelect.Option>
                            })
                        }
                    </AntdSelect>
                    <div className={styles["select-button"]} >
                        <div>
                            <p>我的试卷</p>
                            <p>记录测试过的试卷，可查看复卷</p>
                        </div>
                        <div className={styles['button-area']}>
                            {
                                showManual&&isHangda() &&<Button className={styles['button-area-buttons']} type="primary" style={{ background: "#fda63f", borderColor: '#fda63f' }} onClick={() => history.push("/exam/" + subject +'/2?type=3')}>人工组卷</Button>
                            }
                           
                            <Button className={styles['button-area-buttons']} type="primary" onClick={() => history.push("/checkPaperList?subject=" + subject + '&subjects=' + subjects)}>查看试卷</Button>
                        </div>
                    </div>
                    <div className={styles["select-button"]}>
                        <div>
                            <p>我的错题</p>
                            <p>统计做题过程中答错的题，可进行单独练习</p>
                        </div>
                        <div className={styles['button-area']}>
                            <Button className={styles['button-area-buttons']} type="primary" onClick={this.jumpExam(2)}>进入练习</Button>
                            <Button className={styles['button-area-buttons']} type="primary" danger onClick={this.clearWrong('1')}>清除错题库</Button>
                        </div>
                    </div>
                    <div className={styles["select-button"]} >
                        <div>
                            <p>标记试题</p>
                            <p>统计做题过程中标记的试题，可进行单独练习</p>
                        </div>
                        <div className={styles['button-area']}>
                            <Button className={styles['button-area-buttons']} type="primary" onClick={this.jumpExam(3)}>进入练习</Button>
                            <Button className={styles['button-area-buttons']} type="primary" danger onClick={this.clearWrong('2')}>清除标记题</Button>
                        </div>
                    </div>
                    <Button type="primary" className={styles["start-exam-button"]} onClick={() => history.push(`/select/more/${subject}/${subjects}`)}>
                        开始考试
            </Button>
                </Card>
            </PageContainer>
        );
    }
}

export default Select;
